package com.firefly.app.biz.order.service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.firefly.app.biz.order.dto.OrderDTO;
import com.firefly.app.biz.order.dto.OrderPrentResultDTO;
import com.firefly.app.biz.order.dto.OrderResultDTO;
import com.firefly.app.biz.order.dto.PayDTO;
import com.firefly.app.biz.order.dto.PayWalletDTO;
import com.firefly.app.biz.order.dto.SytWalletDTO;
import com.firefly.app.biz.order.enums.OrderSystemEnum;
import com.firefly.app.biz.order.util.AXLoginUtil;
import com.firefly.mobile.app.config.Config;
import com.firefly.mobile.app.util.DateUtil;
import com.firefly.mobile.app.util.HttpUtil;
import com.firefly.mobile.app.util.Md5;
import com.firefly.mobile.app.util.SytLog;
import com.firefly.mobile.app.util.UserLoginUtil;

public class OrderServiceImpl implements OrderService{

	
	String url =Config.getString("order.server.url");
	String key =Config.getString("order.server.key");
	String desKey = Config.getString("sytuser.proxy.desKey");
	
	@Override
	public OrderResultDTO createOrder(OrderDTO orderDTO) {
		// 访问参数
		orderDTO.setServiceName("order");
		orderDTO.setVersion("1.0");
		orderDTO.setSignType("MD5");
		
		orderDTO.setReqTime(DateUtil.getCurrTime_YYYYMMDDHHMMSS());
		orderDTO.setReqSerial(orderDTO.getUserId()+DateUtil.getCurrTime_YYYYMMDDHHMMSS());
		orderDTO.setBizType(orderDTO.getTransId());
		// 访问参数
		Map<String, String> params = new HashMap<String, String>();
		/**通用**/
		params.put("serviceName",orderDTO.getServiceName());
		params.put("version", orderDTO.getVersion());
		params.put("signType", orderDTO.getSignType());
		/**管理类**/
		params.put("reqTime", orderDTO.getReqTime());
		params.put("reqSerial", orderDTO.getReqSerial());
		params.put("bizType", orderDTO.getBizType());
		if(orderDTO.getTransId().equals("sytUserWallet") || orderDTO.getTransId().equals("sytWithdraw")){
			SytWalletDTO sytWalletDTO  = com.alibaba.fastjson.JSONObject.parseObject(orderDTO.getBizData(), SytWalletDTO.class);
			String pwd ="";
			try {
				pwd = getEnPwd(sytWalletDTO.getPassword());
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sytWalletDTO.setPassword(pwd);
			orderDTO.setBizData(JSON.toJSONString(sytWalletDTO));
		}
		
		params.put("bizData", orderDTO.getBizData()==null?"":orderDTO.getBizData());
		params.put("transAmt", orderDTO.getTransAmt());
		params.put("bizAmt", orderDTO.getBizAmt());
		params.put("feeAmt", orderDTO.getFeeAmt());
		params.put("userId", orderDTO.getUserId());
		params.put("mobileNo", orderDTO.getMobileNo());
		params.put("bizMobileNo", orderDTO.getBizMobileNo());

		OrderResultDTO orderResultDTO = new OrderResultDTO();
		String signSource = getIsEmpty(orderDTO.getServiceName())+ getIsEmpty(orderDTO.getReqTime())+ getIsEmpty(orderDTO.getReqSerial())+ getIsEmpty(orderDTO.getBizType())
				+ getIsEmpty(orderDTO.getBizData())+ getIsEmptyZero(orderDTO.getTransAmt())+ getIsEmptyZero(orderDTO.getBizAmt())+ getIsEmptyZero(orderDTO.getFeeAmt())+getIsEmpty(orderDTO.getUserId())+ getIsEmpty(orderDTO.getMobileNo())+ getIsEmpty(orderDTO.getBizMobileNo())
				+ key;
		SytLog.i("signSource="+signSource);
		String sign = Md5.md5(signSource);
		
		params.put("sign", sign);
		// 获得返回结果
		try {
			String result = HttpUtil.getUrlAsString(url, params);
			orderResultDTO = JSONObject.parseObject(result, OrderResultDTO.class);
//			checkSign(orderResultDTO);
		} catch (Exception e) {
			e.printStackTrace();
			SytLog.e("调用异常", e.toString());
		}
		return orderResultDTO;
	}
	
	private String getIsEmpty(String source){
		return source==null?"":source;
	}
	
	private String getEnPwd(String pwd) throws UnsupportedEncodingException, Exception {
		String enPwd = AXLoginUtil.encrypt(pwd, desKey);
		return enPwd;
	}
	
	private String getIsEmptyZero(String source){
		 if(source == null || source.length() <= 0){
			 source = "0";
		 }
		return source;
	}
	
	
	private boolean checkSign(OrderResultDTO res) {
		String sign = Md5.md5(res.getIsSuccess() +res.getErrorCode() + res.getResultCode() + res.getTradeNo() + res.getReqSerial() + res.getDetErrorCode() + res.getDetErrorDesc() + res.getTradeNo()
				+ res.getReturnBizData()==null?"":res.getReturnBizData() + res.getReturnPayData()==null?"":res.getReturnPayData() + res.getReturnManageData()==null?"":res.getReturnManageData() + key );
		if (sign.equals(res.getSign())) {
			return true;
		}else {
			SytLog.e("前置返回验密未通过");
			throw new RuntimeException("前置返回验密未通过");
		}
	}

	@Override 
	public OrderResultDTO pay(PayDTO payDTO) {
		// 访问参数
		payDTO.setServiceName("pay");
		payDTO.setVersion("1.0");
		payDTO.setSignType("MD5");
		
		if ("sytWallet".equals(payDTO.getPayType())) {
			PayWalletDTO payWalletDTO = JSON.parseObject(payDTO.getPayData(), PayWalletDTO.class);
			payWalletDTO.setPassword(UserLoginUtil.encrypt(payWalletDTO.getPassword(), desKey));
			payDTO.setPayData(JSON.toJSONString(payWalletDTO));
		}
		
		// 访问参数
		Map<String, String> params = new HashMap<String, String>();
		/**通用**/
		params.put("serviceName",payDTO.getServiceName());
		params.put("version", payDTO.getVersion());
		params.put("signType", payDTO.getSignType());
		params.put("termNo", payDTO.getTermNo());
		/**管理类**/
		params.put("transAmt", payDTO.getTransAmt());
		params.put("payAmt", payDTO.getPayAmt());
		params.put("payData", payDTO.getPayData());
		params.put("tradeNo", payDTO.getTradeNo());
		params.put("payType", payDTO.getPayType());

		OrderResultDTO orderResultDTO = null;
		String signSource = getIsEmpty(payDTO.getServiceName()) + getIsEmpty(payDTO.getTermNo()) + getIsEmpty(payDTO.getTradeNo()) + getIsEmpty(payDTO.getTransAmt()) + getIsEmpty(payDTO.getPayAmt()) + getIsEmpty(payDTO.getPayType()) + getIsEmpty(payDTO.getPayData()) + key;
		SytLog.i("支付md5拼接字符："+signSource);
		String sign = Md5.md5(signSource);
		params.put("sign", sign);
		// 获得返回结果
		try {
			String result = HttpUtil.getUrlAsString(url, params);
			orderResultDTO = JSONObject.parseObject(result, OrderResultDTO.class);
			
		} catch (Exception e) {
			e.printStackTrace();
			SytLog.e("调用异常", e.toString());
		}
		return orderResultDTO;
	}
	
	/* 
	 * 订单查询接口返回
	 */
	@Override
	public OrderResultDTO queryOrder(OrderDTO orderDTO) {
		String termNo = Config.FRONT.TERM_NO;
		orderDTO.setServiceName("query");
		orderDTO.setVersion("1.0");
		orderDTO.setSignType("MD5");
		orderDTO.setTermNo(termNo);
		orderDTO.setSign("123");
		
		orderDTO.setReqTime(DateUtil.getCurrTime_YYYYMMDDHHMMSS());
		orderDTO.setReqSerial(orderDTO.getUserId()+DateUtil.getCurrTime_YYYYMMDDHHMMSS());
		orderDTO.setBizType(orderDTO.getTransId());
		
		// 访问参数
		Map<String, String> params = new HashMap<String, String>();
		/**通用**/
		params.put("serviceName",orderDTO.getServiceName());
		params.put("version", orderDTO.getVersion());
		params.put("signType", orderDTO.getSignType());
		params.put("termNo", orderDTO.getTermNo());
		params.put("sign", orderDTO.getSign());
		
		/**管理类**/
		params.put("reqTime", orderDTO.getReqTime());
		params.put("reqSerial", orderDTO.getReqSerial());
		params.put("queryType", orderDTO.getQueryType());
		params.put("queryData", orderDTO.getQueryData());
		
		OrderResultDTO orderResultDTO = null;
		String signSource = getIsEmpty(orderDTO.getServiceName()) + getIsEmpty(orderDTO.getTermNo()) + getIsEmpty(orderDTO.getReqTime()) + getIsEmpty(orderDTO.getReqSerial()) + getIsEmpty(orderDTO.getQueryType()) + getIsEmpty(orderDTO.getQueryData())  + key;
		SytLog.i("支付md5拼接字符："+signSource);
		SytLog.i("支付md5拼接字符："+signSource);
		String sign = Md5.md5(signSource);
		params.put("sign", sign);
		// 获得返回结果
		try {
			String result = HttpUtil.getUrlAsString(url, params);
			orderResultDTO = JSONObject.parseObject(result, OrderResultDTO.class);
			
		} catch (Exception e) {
			e.printStackTrace();
			SytLog.e("调用异常", e.toString());
		}
		return orderResultDTO;

		
	}
	
	/**
	 * 判断结果是否正确
	 * 
	 * @param result 返回结果
	 * @return 正确返回true, 否则返回false
	 */
	private static boolean isValidResult(OrderPrentResultDTO orderPrentResultDTO) {
		if (orderPrentResultDTO == null) {
			return false;
		}
		if (OrderSystemEnum.请求成功.getCode().equals(orderPrentResultDTO.getIsSuccess()) && OrderSystemEnum.处理成功.getCode().equals(orderPrentResultDTO.getResultCode())) {
			return true;
		}else {
			return false;
		}
	}
}
